package com.ebspp.client.placement;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.thrift.transport.TTransportException;

import com.ebspp.client.serverManager.AsyncGBCollector;
import com.ebspp.thrift.DataMsg;
import com.ebspp.thrift.Identity;
import com.ebspp.thrift.ResourceType;

/**
 * in memory placement.
 * It places all the key->server mapping information inside the memory
 * Hence, a client side failure will make all data unreachable.
 * 
 * @author x23pan
 *
 */
public class MvMemPlacement implements IPlacement
{
	Identity id;
	ResourceType resType;
	
	Map<String, Map<String, String>> keyServerMap = null;
	
	public MvMemPlacement(Identity id, ResourceType type) throws TTransportException
	{
		this.id = id;
		this.resType = type;
		
		//gbCollector = new AsyncGBCollector(id, type);
		keyServerMap = Collections.synchronizedMap(new HashMap<String, Map<String, String>>());
	}
	
	@Override
	public void setPlace(String server, List<DataMsg> data) {
		// TODO Auto-generated method stub
		for(DataMsg msg : data)
		{
			Map<String, String> tsServerMap = keyServerMap.get(msg.getKey());
			if(tsServerMap == null)
			{
				tsServerMap = Collections.synchronizedMap(new HashMap<String, String>());
				keyServerMap.put(msg.getKey(), tsServerMap);
			}
			tsServerMap.put(msg.getTs(), server);
		}
	}

	@Override
	public String getPlace(DataMsg msg) 
	{
		// TODO Auto-generated method stub
		Map<String, String> tsServerMap = keyServerMap.get(msg.getKey());
		if(tsServerMap == null)
			return null;
		else
			return tsServerMap.get(msg.getTs());
	}


}
